﻿using System.Windows;
using GalaSoft.MvvmLight.Threading;
using System.Diagnostics;
using System.Linq;
using ASoft.Service;
using System;
using ASoft.Msg;
using System.Reflection;
using System.Windows.Threading;
using System.Threading;
using ASoft.Led;
using ASoft.Base;
using ASoft.WPF.Base;

namespace ASoft.WPF
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        static LedService ledService;
        static App()
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            DispatcherHelper.Initialize();
            var data = RC.Current.RootData.PLCData;
            //RealTimeService.ExceptionAction = (ex) =>
            //    {
            //        DispatcherHelper.UIDispatcher.BeginInvoke
            //        (DispatcherPriority.Normal, new System.Threading.ParameterizedThreadStart((e) =>
            //        {
            //            RC.Current.ErrorLoger.Error(((Exception)e).Message);
            //            //MessageBox.Show(((Exception)e).Message);
            //        }), ex);
            //    };
            ledService = new LedService(ConfigInfo.RootPath);

            MyTaskService.Current.Starting += Task_Starting;
            MyTaskService.Current.Ending += Task_Ending;

            var assembly = Assembly.GetAssembly(typeof(MsgVMAttribute));
            var ary = assembly.GetTypes().Where(p => p.GetCustomAttributes(typeof(MsgVMAttribute), true).Length > 0).ToList();
            ary.ForEach(p =>
                {
                    var name = p.Name;
                });

        }

        static void Task_Ending(object sender, EventArgs e)
        {
            //ledService.End();
            RC.Current.PhoneMsgService.ClosePort();
        }

        static void Task_Starting(object sender, EventArgs e)
        {
            //ledService.Start();
            RoomTask roomTask = new RoomTask();
            MyTaskService.Current.AddItem(roomTask.GetRealTimeItem());

            LedTask ledTask = new LedTask(ledService);
            MyTaskService.Current.AddItem(ledTask.GetRealTimeItem());
            RC.Current.PhoneMsgService.OpenPort();

        }


        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            RC.Current.Loger.Error(e.ExceptionObject.ToString());
            MessageBox.Show(((Exception)e.ExceptionObject).Message);
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            IsAppAlreadyRunning();
            RC.Current.Loger.Trace("程序启动");
            this.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
        }

        protected override void OnExit(ExitEventArgs e)
        {
            MyTaskService.Current.Stop();
            System.Threading.Thread.Sleep(1000);
            RC.Current.Loger.Trace("程序退出");
            //Environment.Exit(Environment.ExitCode);
            //base.OnExit(e);

        }

        void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            RC.Current.Loger.Error(e.Exception.ToString());
            MessageBox.Show(e.Exception.Message);
            e.Handled = true;
        }

        private static void IsAppAlreadyRunning()
        {
            Process currentProcess = Process.GetCurrentProcess();

            if (Process.GetProcessesByName(currentProcess.ProcessName).Any(p => p.Id != currentProcess.Id))
            {
                MessageBox.Show("每次只能运行一个实例.\r\n如果出现异常，请在'任务管理器'里结束'asoft.wpf.exe',再重试.", "应用程序已运行",
                MessageBoxButton.OK, MessageBoxImage.Exclamation);
                Current.Shutdown();
                return;
            }
        }
    }
}
